package com.baselibrary.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.ColorInt;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.annotation.StringRes;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.baselibrary.Constants;
import com.baselibrary.R;
import com.baselibrary.action.BundleAction;
import com.baselibrary.action.HandlerAction;
import com.baselibrary.base.BaseDialog;
import com.baselibrary.manager.AppManager;
import com.baselibrary.manager.DialogManager;
import com.baselibrary.manager.LoadingManager;
import com.baselibrary.permission.PermissionsUtils;
import com.baselibrary.utils.CommonUtil;
import com.baselibrary.utils.Config;
import com.baselibrary.utils.HKToastUtils;
import com.baselibrary.utils.NetworkChangedReceiver;
import com.baselibrary.utils.StatusBarUtil;
import com.baselibrary.utils.ToastUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.umeng.socialize.UMShareAPI;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhanglijie
 */
public abstract class BaseActivity extends AppCompatActivity implements HandlerAction, BundleAction {
    private NetworkChangedReceiver mNetWorkChangReceiver;
    private static List<Activity> activityStack = new ArrayList<Activity>();
    private static boolean wxRegister = false;
    private static MyBroadcastReceiver receiver;
    private BaseDialog mLoadingDialog;
    private ImmersionBar mImmersionBar;
    private ViewDataBinding viewDataBinding;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        viewDataBinding = DataBindingUtil.setContentView(this, getLayoutId());
        if (!wxRegister) {
            wxRegister = true;
            if (receiver == null) {
                receiver = new MyBroadcastReceiver();
            }
            LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(receiver, new IntentFilter(Config.wechat_share_success));
        }
        setMainBackgroundColor(Color.parseColor("#EBECF0"));
        initSoftKeyboard();
        setStatusBarDarkTheme(true);
        init();
        registerNetWorkChangReceiver();
    }
    private void registerNetWorkChangReceiver() {
        //注册网络状态监听广播
        mNetWorkChangReceiver = new NetworkChangedReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mNetWorkChangReceiver, filter);
        mNetWorkChangReceiver.setOnNetWorkChangedCallBack(new NetworkChangedReceiver.OnNetWorkChangedCallBack() {
            @Override
            public void onNetWorkChanged(boolean isNetWork, int NetType) {
                if (!isNetWork)
                    ToastUtils.showShort(getApplicationContext(), "无网络连接");
            }
        });
    }

    public void setStatusBarDarkTheme(boolean dark) {
        if (!StatusBarUtil.setStatusBarDarkTheme(this, dark)) {
        StatusBarUtil.setStatusBarColor(this, dark ? R.color.black : R.color.white);
    }
    }

    class MyBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Config.wechat_share_success.equals(action)) {
            }
        }
    }


    /**
     * 获取布局View
     *
     * @return
     */
    protected abstract int getLayoutId();

    protected <T> T getDataBinding() {
        return (T) viewDataBinding;
    }

    /**
     *
     */
    protected abstract void init();


    // 给所有的fragment提供的函数，可以顺利的拿到 ViewModel
    protected ViewModelProvider getFragmentViewModelProvider(Fragment fragment) {
        return new ViewModelProvider(fragment, fragment.getDefaultViewModelProviderFactory());
    }

    /**
     * 暴露给自己的孩子 得到ViewModelProvider
     *
     * @param activity 子类的 activity
     * @return
     */
    protected ViewModelProvider getActivityViewModelProvider(AppCompatActivity activity) {
        return new ViewModelProvider(activity, activity.getDefaultViewModelProviderFactory());
    }

    protected ImmersionBar createStatusBarConfig() {
        mImmersionBar = ImmersionBar.with(this)
                .statusBarDarkFont(isStatusBarDarkFont());
        return mImmersionBar;
    }

    private ViewGroup getContentParent() {
        return findViewById(android.R.id.content);
    }

    protected void setMainBackgroundColor(@ColorInt int color) {
        if (getContentParent() != null) {
            getContentParent().setBackgroundColor(color);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    protected void setMainBackgroundDrawable(@DrawableRes int drawable) {
        if (getContentParent() != null) {
            getContentParent().setBackground(getDrawable(drawable));
        }
    }

    /**
     * 初始化沉浸式
     */
    protected void initImmersion(boolean isStatusBarEnabled) {
        // 初始化沉浸式状态栏
        if (isStatusBarEnabled) {
            createStatusBarConfig().init();
        }
    }

    /**
     * 是否使用沉浸式状态栏
     *
     * @return
     */
    private boolean isStatusBarEnabled() {
        return true;
    }



    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode,resultCode,data);
    }

    /**
     * 状态栏字体深色模式
     *
     * @return
     */
    private boolean isStatusBarDarkFont() {
        return true;
    }

    @Nullable
    protected ImmersionBar getStatusBarConfig() {
        return mImmersionBar;
    }

    /**
     * 初始化软键盘
     */
    protected void initSoftKeyboard() {
        // 点击外部隐藏软键盘，提升用户体验
        getContentView().setOnClickListener(v -> hideSoftKeyboard());
    }
    protected void showLoadingDialog() {
        showLoadingDialog(null);
    }

    protected void showLoadingDialog(String msg) {
        LoadingManager.showLoadingDialog(this, msg);
    }

    protected void hideLoadingDialog() {
        LoadingManager.hideLoadingDialog(this);
    }

    /**
     * 只有一个且包含这个 Act说明是NFC直接调起
     *
     * @param activity
     * @return
     */
    public static boolean nfcActivity(Activity activity) {
        if (activityStack == null)
            return false;
        return activityStack.size() == 1 && activityStack.contains(activity);
    }

    public static void removeNfcActivity(Activity activity) {
        if (activityStack.size() > 0) {
            activityStack.remove(activity);
        }
    }


    protected void showToast(String message) {
        HKToastUtils.showToast(message);
    }

    protected void showToast(@StringRes int stringId) {
        HKToastUtils.showToast(getString(stringId));
    }

    public void openActivity(Class<?> cls, Bundle bundle) {
        Intent intent = new Intent(this, cls);
        intent.putExtras(bundle);
        startActivity(intent);

    }
    public void openActivity(Class<?> mClass) {
        Intent intent = new Intent(this, mClass);
        startActivity(intent);
    }

    private ViewGroup getContentView() {
        return findViewById(android.R.id.content);
    }

    @Nullable
    @Override
    public Bundle getBundle() {
        return getIntent().getExtras();
    }

    @Override
    protected void onDestroy() {
        removeCallbacks();
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
        mLoadingDialog = null;
        super.onDestroy();
    }

    /**
     * 隐藏软键盘
     */
    public void hideSoftKeyboard() {
        // 隐藏软键盘，避免软键盘引发的内存泄露
        View view = getCurrentFocus();
        if (view != null) {
            InputMethodManager manager =
                    (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (manager != null) {
                manager.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
        }
    }

    @Override
    public void finish() {
        hideSoftKeyboard();
        super.finish();
    }


    public void showCoinDialog(int result,String tip) {
        DialogManager.showCoinDialog(this, tip, result);
    }

    @Override
    protected void onPause() {
        Constants.pushOnline=true;
        super.onPause();
    }
    // 5.0版本以上
    @SuppressLint("NewApi")
    public void setStatusBarHeight() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
            if (findViewById(R.id.status_bar) != null) {
                findViewById(R.id.status_bar).setVisibility(View.VISIBLE);
                findViewById(R.id.status_bar).getLayoutParams().height = CommonUtil.getStatusBarHeight(getApplication());
            }
        }
    }

    public void setStatusBarHeight(int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
            if (findViewById(R.id.status_bar) != null) {
                findViewById(R.id.status_bar).setVisibility(View.VISIBLE);
                findViewById(R.id.status_bar).setBackgroundResource(color);
                findViewById(R.id.status_bar).getLayoutParams().height = CommonUtil.getStatusBarHeight(getApplication());
            }
        }
    }

    public void addActivity(Activity aty) {
        activityStack.add(aty);
    }

    public static void finishActivity(Class aty) {
        for (int i = 0, size = activityStack.size(); i < size; i++) {
            if (null != activityStack.get(i) && null != aty
                    && aty.getSimpleName().equals(activityStack.get(i).getClass().getSimpleName())) {
                activityStack.get(i).finish();
            }
        }
    }
    public static void finishAllActivity() {
        AppManager.getAppManager().finishAllActivity();
        for (int i = 0, size = activityStack.size(); i < size; i++) {
            if (null != activityStack.get(i)) {
                activityStack.get(i).finish();
            }
        }
        activityStack.clear();
    }

    public static List<Activity> getActivityStack() {
        return activityStack;
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionsUtils.getInstance().onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }
}
